package com.stylefeng.guns.modular.fileManage.controller;

import com.stylefeng.guns.common.persistence.dao.ZyBrewsPictureMapper;
import com.stylefeng.guns.common.persistence.model.ZyBrewsPicture;
import com.stylefeng.guns.common.persistence.model.ZyPicture;
import com.stylefeng.guns.common.persistence.model.ZyTeaPicture;
import com.stylefeng.guns.core.base.controller.BaseController;
import com.stylefeng.guns.core.page.PageBT;
import com.stylefeng.guns.core.page.PageInfoBT;
import com.stylefeng.guns.core.upload.RtnInfo;
import com.stylefeng.guns.core.util.PagingHandler;
import com.stylefeng.guns.modular.fileManage.dao.ZyBrewsPictureDao;
import com.stylefeng.guns.modular.fileManage.dao.ZyPictureDao;
import com.stylefeng.guns.modular.fileManage.dao.ZyTeaPictureDao;
import com.stylefeng.guns.modular.fileManage.service.UploadService;
import com.stylefeng.guns.modular.fileManage.service.impl.ZyPictureServiceImpl;
import com.stylefeng.guns.modular.fileManage.warpper.PictureWarpper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.ui.Model;
import org.springframework.beans.factory.annotation.Autowired;
import com.stylefeng.guns.modular.fileManage.service.IZyPictureService;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.util.List;
import java.util.Map;

/**
 * 图片管理控制器
 *
 * @author fengshuonan
 * @Date 2017-12-26 14:53:22
 */
@Controller
@RequestMapping("/picture")
public class PictureController extends BaseController {

    private String PREFIX = "/fileManage/picture/";

    Logger log = LoggerFactory.getLogger(PictureController.class);

    @Resource
    UploadService uploadService;

    @Autowired
    private IZyPictureService pictureService;

    @Autowired
    private ZyBrewsPictureDao zyBrewsPictureDao;

    @Autowired
    private ZyPictureServiceImpl pictureServiceImpl;

    @Autowired
    private ZyTeaPictureDao teaPictureDao;

    /**
     * 获取图片管理列表
     */
    @RequestMapping(value = "")
    public String list(PageBT pageParam, Model model) throws Exception {
        PageInfoBT pageInfo = PagingHandler.getPageResult("zy_picture", pageParam);
        PictureWarpper picWar = new PictureWarpper(pageInfo.getRows());
        pageInfo.setRows((List) super.warpObject(picWar));
        model.addAttribute("pageInfo", pageInfo);
        return PREFIX + "picture.html";
    }

    /**
     * 跳转到添加图片
     */
    @RequestMapping("/picture_add")
    public String pictureAdd() {
        return PREFIX + "picture_add.html";
    }


    /**
     * 新增图片管理
     */
    @RequestMapping(value = "/add")
    @ResponseBody
    public Object add(@RequestParam(value = "file")MultipartFile[] files) throws Exception {
        synchronized(this){
            uploadService.upload(files,null);
        }
        return SUCCESS_TIP;
    }

    /**
     * 删除图片管理
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public Object delete(@RequestParam Integer pictureId) {
        uploadService.delete(pictureId);
        return SUCCESS_TIP;
    }

    /**
     * 获取一张图片的信息
     */
    @RequestMapping(value = "/detail/{pictureId}")
    @ResponseBody
    public Object detail(@PathVariable("pictureId") Integer pictureId) {
        return pictureService.selectById(pictureId);
    }

    /**
     * 取消关联的图片
     */
    @RequestMapping(value = "/cancelSelector")
    @ResponseBody
    public Object cancelSelector(@RequestParam(value = "type", required = true) String type
            ,@RequestParam(value = "itemId", required = true) Integer itemId) {
        if(itemId == null){
            return SUCCESS_TIP;
        }
        Integer[] pictureIds;
        if("brews".equals(type)){
            //查出该冲泡方式对应关联的图片ID
            List<ZyBrewsPicture> zyBrewsPic = zyBrewsPictureDao.selectByBrewsId(itemId);
            for(int i = 0;i<zyBrewsPic.size();i++){
                pictureIds = new Integer[1];
                pictureIds[0] = zyBrewsPic.get(i).getPictureId();
                //取消关联
                pictureServiceImpl.cancelSelectorByBrewsId(itemId, pictureIds);
            }
        }else if("tea".equals(type)){
            //查出该茶叶对应关联的图片ID
            List<ZyTeaPicture> zyTeaPic = teaPictureDao.selectByTeaId(itemId);
            pictureIds = new Integer[zyTeaPic.size()];
            for(int i=0;i<zyTeaPic.size();i++){
                pictureIds[i] = zyTeaPic.get(i).getPictureId();
                //取消关联
                pictureServiceImpl.cancelSelectorByTeaId(itemId, pictureIds);
            }
        }
        return SUCCESS_TIP;
    }

    /**
     * 图片上传 for wangEditor 富文本框
     * NOT USE
     */
    @RequestMapping(method = RequestMethod.POST, value = "/upload")
    @ResponseBody
    public Object upload(@RequestParam(value = "file")MultipartFile[] files) throws IOException, ParseException {
        RtnInfo info = new RtnInfo();
        info.setErrno(0);
        try{
            List<ZyPicture> pics = uploadService.upload(files,null);
            String[] strs = new String[pics.size()];
            for(int i = 0;i < pics.size();i++){
                StringBuffer sb = new StringBuffer("/static/");
                sb.append(pics.get(i).getSavePath().substring(pics.get(i).getSavePath().indexOf("img")));
                if (!sb.toString().endsWith(File.separator)) {
                    sb = new StringBuffer(sb.append("/"));
                }
                sb.append(pics.get(i).getSaveName());
                strs[i] = sb.toString();
            }
            info.setData(strs);
        }catch (Exception e){
            info.setErrno(400);
            log.error("富文本框上传图片失败：" + e.getMessage());
        }
        return info;
    }
}
